﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Zeus.Thunder.Core;

namespace SharpTrainer.Concurrency
{
    class AsyncResultTest : ITestCase
    {
        delegate ResponseData MyDelegate(string data);

        public void Run()
        {
            ThreadMessage("Main Thread");
            
            // 建立委托
            MyDelegate myDelegate = new MyDelegate(Hello);

            // 异步调用委托，获取计算结果
            IAsyncResult result = myDelegate.BeginInvoke("Master HaKu", null, null);
            
            // 完成主线程其他工作
            

            // 等待异步方法完成，调用EndInvoke(IAsyncResult)获取运行结果
            ResponseData data = myDelegate.EndInvoke(result);
            Console.WriteLine("------------------------------------------------");
            Console.WriteLine("Response:");
            Console.WriteLine(data);
        }

        private ResponseData Hello(string name)
        {
            ThreadMessage("Async Thread");

            // 虚拟异步工作
            Thread.Sleep(5000);            

            return new ResponseData
            {
                Code = "1",
                Message = "Hello " + name
            };
        }

        //显示当前线程
        private void ThreadMessage(string data)
        {
            string message = string.Format("{0}\n  ThreadId is:{1}",
                   data, Thread.CurrentThread.ManagedThreadId);
            Console.WriteLine(message);
        }
    }
}
